package cn.fay.chapter10;

import java.util.Random;

interface Selector{
	boolean end();
	Object current();
	void next();
}
interface SelectorFactory{
	Selector getSelector();
}
public class Sequence {

	private Object[] items;
	private int next=0;
	public Sequence(int size){
		items=new Object[size];
	}
	public void add(Object x){
		if (next<items.length) {
			items[next++]=x;
		}
	}
	private class SequenceSelector implements Selector{
		private int i=0;
		@Override
		public boolean end() {		
			return i==items.length;
		}
		@Override
		public Object current() {
			return items[i].toString();
		}
		@Override
		public void next() {
			if (i<items.length)
				i++;
		}
		
	}
	public SelectorFactory sequencefactory=new SelectorFactory() {
		@Override
		public Selector getSelector() {
			return new SequenceSelector();
		}
	};
	public  SelectorFactory reversefactory=new SelectorFactory() {
		@Override
		public Selector getSelector() {
			return new ReverseSelector();
		}
	};
	public static void useSelector(SelectorFactory factory){
		Selector selector=factory.getSelector();
		while (!selector.end()) {
			System.out.print(selector.current()+" ");
			selector.next();
		}
	}
	public static void main(String[] args) {
		Sequence sequence=new Sequence(10);
		Random random=new Random(47);
		for(int i=0; i<10; i++)
			sequence.add(Integer.valueOf(random.nextInt(100)));
		Sequence.useSelector(sequence.sequencefactory);
		System.out.println();
		Sequence.useSelector(sequence.reversefactory);
	}
	private class ReverseSelector implements Selector {
		private int i=items.length;
		@Override
		public boolean end() {
			return i==0;
		}
		@Override
		public Object current() {
			return items[i-1];
		}
		@Override
		public void next() {
			if (i>0) 
				i--;
		}
	}
}
